const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 格式化金额
 */
function format_money(money) {
  money = parseFloat(money);
  if (!money) {
    return false;
  }
  return parseInt(money * 100) / 100;
}

/**
 * 格式化时间
 */
function format_time(format_str, mtime) {
  if (!mtime) {
    var mtime = new Date();
  } else {
    var mtime = new Date(parseInt(mtime) * 1000);
  }
  var timeObject = {
    "M+": mtime.getMonth() + 1,                   //月份 
    "d+": mtime.getDate(),                        //日 
    "h+": mtime.getHours(),                       //小时 
    "m+": mtime.getMinutes() < 10 ? '0' + mtime.getMinutes() : mtime.getMinutes(),                     //分 
    "s+": mtime.getSeconds() < 10 ? '0' + mtime.getSeconds() : mtime.getSeconds(),                     //秒 
    "q+": Math.floor((mtime.getMonth() + 3) / 3), //季度 
    "S": mtime.getMilliseconds()                  //毫秒 
  };
  if (/(y+)/.test(format_str)) {
    format_str = format_str.replace(RegExp.$1, (mtime.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in timeObject) {
    if (new RegExp("(" + k + ")").test(format_str)) {
      format_str = format_str.replace(RegExp.$1, (RegExp.$1.length == 1) ? (timeObject[k]) : (("00" + timeObject[k]).substr(("" + timeObject[k]).length)));
    }
  }
  return format_str;
} 

/**
 * 打开新页面
 */
function openUrl(url) {
  if (url.length < 1) {
    return false;
  }
  wx.navigateTo({
    url: url
  });
}

/**
 * 发送推送码
 */
function addMessageCode(info) {
  //获取推送码
  if (!info.code) {
    return false;
  }
  var tempate_message = {
    act: 'add_template_code',
    userid: info.userid,
    code: info.code,
    times: info.times,
  };
  var app = getApp();
  app.http_req(tempate_message, app.globalData.init.api_url, 'POST');
}
module.exports = {
  formatTime: formatTime,
  format_time: format_time,
  format_money: format_money,
  openUrl: openUrl,
  addMessageCode: addMessageCode  
}
